package com.study.doc;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class DocumentMerger {

    public static void mergeDocuments(List<String> docPaths, String outputPath) throws Exception {
        List<XWPFDocument> documents = new ArrayList<>();
        for (String path : docPaths) {
            FileInputStream fis = new FileInputStream(path);
            XWPFDocument doc = new XWPFDocument(fis);
            documents.add(doc);
            fis.close();
        }
        XWPFDocument mergedDoc = new XWPFDocument();
        for (XWPFDocument doc : documents) {
            for (XWPFParagraph p : doc.getParagraphs()) {
                mergedDoc.createParagraph().createRun().setText(p.getText());
            }
            for (XWPFTable tbl : doc.getTables()) {
                mergedDoc.createTable(); // Manually handle table merging, this is a simplified example and might need more work for complex tables.
            }
        }
        FileOutputStream out = new FileOutputStream(outputPath);
        mergedDoc.write(out);
        out.close();
        mergedDoc.close(); // Close the merged document to release resources properly
    }

    public static void main(String[] args) throws Exception{
        List<String> list = new ArrayList<>();
        list.add("D:\\学习资料\\jdk\\文件合并\\a.docx");list.add("D:\\学习资料\\jdk\\文件合并\\b.docx");
        mergeDocuments(list,"D:\\学习资料\\jdk\\文件合并\\c.docx");
    }
}
